package com.xpec.c4.h5net;

import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

class H5XSENetSpeedometerFilter extends SimpleChannelHandler implements H5IMeter
{
	/**
	 * 日志
	 */
	private static final Log logger = LogFactory.getLog(H5XSENetSpeedometerFilter.class);
	
	@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception
    {
		Object m = e.getMessage();
		if(m instanceof ChannelBuffer)
		{
			ChannelBuffer input = (ChannelBuffer)m;
			int byteSize = input.readableBytes();
			this.dealAfterReceive(byteSize);
		}
    	ctx.sendUpstream(e);
    }
	
	@Override
    public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception
    {
		if( !e.getChannel().isConnected() )
			return;
		
		Object m = e.getMessage();
    	if(m instanceof ChannelBuffer)
    	{
            ChannelBuffer input = (ChannelBuffer)m;
           	int byteSize = input.readableBytes();
		
           	this.dealBeforeSent(byteSize);
    	}
    	ctx.sendDownstream(e);
    }

	public Integer getInputBps() {
		return (int)this.receiveByteCount.get();
	}

	public Integer getInputPps() {
		return (int)this.receiveMessageCount.get();
	}
	
	public Integer getOutputPps() {
		return (int)this.sentMessageCount.get();
	}

	public Integer getOutputBps() {
		return (int)this.sentByteCount.get();
	}
	
	/**
	 * 接收的字节总数
	 */
	public AtomicLong receiveByteCount = new AtomicLong(0);

	/**
	 * 接收的消息总数
	 */
	public AtomicLong receiveMessageCount = new AtomicLong(0);

	/**
	 * 接收计数的开始时间
	 */
	public static long receiveCountBeginTime = System.currentTimeMillis();

	/**
	 * 发送的字节总数
	 */
	public AtomicLong sentByteCount = new AtomicLong(0);

	/**
	 * 发送的消息总数
	 */
	public AtomicLong sentMessageCount = new AtomicLong(0);

	/**
	 * 发送计数的开始时间
	 */
	public static long sentCountBeginTime = System.currentTimeMillis();

	/**
	 * 每次统计的最大消息总量
	 */
	public static long messageCountMax = 1024;//ServerProperties.getInt("messageCountMax", );

	private void dealAfterReceive(int byteSize) 
	{
		addReceiveByteCount(byteSize);
		addReceiveMessageCount();
	}

	private void dealBeforeSent(int byteSize) 
	{
		addSentByteCount(byteSize);
		addSentMessageCount();		
	}

	private  long addSentByteCount(int byteSize) {
		return sentByteCount.addAndGet(byteSize);
	}

	private  long addReceiveByteCount(int byteSize) {
		return receiveByteCount.addAndGet(byteSize);
	}

	private  long addSentMessageCount() {
		return sentMessageCount.incrementAndGet();
	}

	private  long addReceiveMessageCount() {
		return receiveMessageCount.incrementAndGet();
	}
}